package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
import com.example.myapplication.AsyncTasks.GetJsonCallBack;
import com.example.myapplication.AsyncTasks.GetJsonTask;
import com.example.myapplication.AsyncTasks.PostJsonTask;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.TimeZone;

public class NoteDataBaseHelper implements GetJsonCallBack {
  private SQLiteDatabase database;
  private SqliteHelper databaseHelper;
  //private RemoteDataBaseHelper remoteDataBaseHelper;
  private NoteViewFragment noteViewFragment;

  public NoteDataBaseHelper(Context context) {
    databaseHelper = new SqliteHelper(context);

    //remoteDataBaseHelper = new RemoteDataBaseHelper();

  }

  public NoteDataBaseHelper(Context context,NoteViewFragment noteViewFragment) {
    databaseHelper = new SqliteHelper(context);
    this.noteViewFragment = noteViewFragment;
  }

  public void Open() {
    database = databaseHelper.getWritableDatabase();
  }
  public void Close() {
    databaseHelper.close();
  }

  public int InsertSingleNote(Note note) {
    //需要插入Note的作者名称、作者账号、标题、内容即可
    ContentValues values = new ContentValues();
    values.put("authorName", note.getAuthorName());
    values.put("authorAccount", note.getAuthorAccount());
    values.put("title", note.getNoteTitle());
    values.put("content", note.getNoteContent());
    int number = (int) database.insert(SqliteHelper.NOTE_TABLE, null, values);
    if (number > 0) {
      return 1;
    }

    return -1;
  }

  public ArrayList<Note> GetNoteListByAccount(String account) {
    ArrayList<Note> notes = new ArrayList<>();
    String orderBy = "createtime DESC";
    String selection = "authorAccount=?";
    String[] selectionArgs = { account };
    Cursor cursor = database.query(SqliteHelper.NOTE_TABLE, null, selection, selectionArgs, null, null, orderBy);

    while (cursor.moveToNext()) {
      Note note = Note.fromCursor(cursor);
      notes.add(note);
    }
    return notes;
  }

  public ArrayList<Note> GetNoteListInDeleteByAccount(String account) {
    ArrayList<Note> notes = new ArrayList<>();
    String orderBy = "createtime DESC";
    String selection = "authorAccount=?";
    String[] selectionArgs = { account };
    Cursor cursor = database.query(SqliteHelper.DELETE_TABLE, null, selection, selectionArgs, null, null, orderBy);

    while (cursor.moveToNext()) {
      Note note = Note.fromCursor(cursor);
      notes.add(note);
    }
    return notes;
  }

  public int DeleteSingleNoteByID(int noteId) {
    if (!IsNoteExits(noteId)) {
      return 0;
    }
    String whereClause = "noteId=?";
    String[] whereArgs = { String.valueOf(noteId) };
    int num = database.delete(SqliteHelper.NOTE_TABLE, whereClause, whereArgs);

    if (num > 0) {
      return 1;
    } else {
      return -1;
    }

  }

  public int SafetyDelete(int noteId) {

    Note note = GetNoteById(noteId);
    InsertSingleNoteToDeleteTable(note);
    DeleteSingleNoteByID(noteId);
    return 1;
  }

  private int InsertSingleNoteToDeleteTable(Note note) {
    //需要插入Note的作者名称、作者账号、标题、内容即可
    ContentValues values = new ContentValues();
    if (note.getNoteId() != -1) {
      values.put("noteid", note.getNoteId());
    }

    values.put("authorName", note.getAuthorName());
    values.put("authorAccount", note.getAuthorAccount());
    values.put("title", note.getNoteTitle());
    values.put("content", note.getNoteContent());
    values.put("createtime", String.valueOf(note.getCreateTime()));
    values.put("updatetime", String.valueOf(note.getUpdateTime()));

    int number = (int) database.insert(SqliteHelper.DELETE_TABLE, null, values);
    if (number > 0) {
      return 1;
    }

    return -1;
  }

  public Note GetNoteById(int noteId) {
    if (!IsNoteExits(noteId)) {
      return null;
    }
    Cursor cursor = database.query(SqliteHelper.NOTE_TABLE, null, null, null, null, null, null);
    Note note = Note.fromCursor(cursor);
    return note;
  }

  public int DeleteMultiNoteByID(ArrayList<Note> notes) {
    int size = notes.size();
    int count = 0;
    database.beginTransaction();
    try {
      for (Note note : notes) {
        DeleteSingleNoteByID(note.getNoteId());
      }
      database.setTransactionSuccessful();
      count++;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }finally {
      database.endTransaction();
    }
    if (count == size) {
      //说明全部删除了
      return 1;
    }
    return -1;//不相等说明事务出现问题，删除失败
  }

  public int UpdateNoteFavour(Note note) {
    int id = note.getNoteId();
    ContentValues values = new ContentValues();
    int flag = 0;
    if (note.isFavour()) {
      flag = 1;
    } else {
      flag = 0;
    }

    String whereClaus = "noteId=?";
    String[] whereArgs = { String.valueOf(id) };
    values.put("favour", String.valueOf(flag));
    int number = database.update(SqliteHelper.NOTE_TABLE, values, whereClaus, whereArgs);
    if (number > 0) {
      return 1;
    } else {
      return -1;
    }
  }
  public int UpdateNoteByID(Note note) {
    //需要更新四个字段：标题、更新时间、内容、是否收藏
    int id = note.getNoteId();
    int number = 0;
    if (!IsNoteExits(id)) {
      number=InsertSingleNote(note);
      return number;
    }
    ContentValues values = new ContentValues();
    values.put("title", note.getNoteTitle());
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //傻逼时区
    //dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String formattedDate = dateFormat.format(note.getUpdateTime());
    values.put("updateTime", formattedDate);
    values.put("content", note.getNoteContent());
    int flag = 0;
    if (note.isFavour()) {
      flag = 1;
    } else {
      flag = 0;
    }
    values.put("favour", String.valueOf(flag));

    String whereClaus = "noteId=?";
    String[] whereArgs = { String.valueOf(note.getNoteId()) };
    number = database.update(SqliteHelper.NOTE_TABLE, values, whereClaus, whereArgs);
    if (number > 0) {
      return 1;
    } else {
      return -1;
    }

  }
  public boolean IsNoteExits(int noteId) {

    Cursor cursor = database.query(SqliteHelper.NOTE_TABLE, null, null, null, null, null, null);
    if (cursor.getCount() != 0) {
      return true;
    }
    return false;
  }

  public void DeleteTable() {
    databaseHelper.DeleteTable();
    System.out.println("已经成功删除表格");
  }

  public void CreateNoteTable() {
    database.execSQL(
        "CREATE TABLE Notes(noteID INTEGER PRIMARY KEY AUTOINCREMENT,authorName VARCHAR(20) not null ,authorAccount VARCHAR(20) not null ,title VARCHAR(20),createtime TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP,updatetime TIMESTAMP not null DEFAULT CURRENT_TIMESTAMP,content LONGTEXT,favour INTEGER DEFAULT 0)");
    System.out.println("创建表格成功");
  }
  public ArrayList<Note> SelectAllNote() {
    ArrayList<Note> notes = new ArrayList<>();
    String orderBy = "createtime DESC";


    Cursor cursor = database.query(SqliteHelper.NOTE_TABLE, null, null, null, null, null, orderBy);

    while (cursor.moveToNext()) {
      Note note = Note.fromCursor(cursor);
      notes.add(note);
    }
    return notes;
  }
  public void UpLoadDataToRemote(RefreshLayout refreshLayout) {
    //ArrayList<Note> notes=SelectAllNote();
    //int number = remoteDataBaseHelper.UpLoadNoteData(notes);
    //if (number == 1) {
    //  System.out.println("上传成功");
    //} else {
    //  System.out.println("上传失败");
    //
    //}
    ArrayList<Note> notes = SelectAllNote();
    new PostJsonTask(refreshLayout).execute(notes);

  }
  public void DownLoadDataFromRemote(RefreshLayout refreshLayout,NoteViewFragment noteViewFragment) {
    //new GetJsonTask(refreshLayout).execute(this);
    new GetJsonTask(refreshLayout, noteViewFragment).execute(this);
  }

  public ArrayList<Note> GetFavourNoteByAccount(String account) {
    ArrayList<Note> notes = new ArrayList<>();
    String orderBy = "createtime DESC";
    String selection = "authorAccount=? AND favour=?";
    String[] selectionArgs = { account, "1" };
    Cursor cursor = database.query(SqliteHelper.NOTE_TABLE, null, selection, selectionArgs, null, null, orderBy);

    while (cursor.moveToNext()) {
      Note note = Note.fromCursor(cursor);
      notes.add(note);
    }
    return notes;
  }

  @Override public void OnGetFinished(ArrayList<Note> notes) {
    UpdateLocalNoteTable(notes);
    //if (noteViewFragment != null) {
    //  noteViewFragment.UpdateNoteData();
    //}
  }

  private void UpdateLocalNoteTable(ArrayList<Note> notes) {
    database.delete(SqliteHelper.NOTE_TABLE, null, null);
    //创建一个ContentValues 存储插入的数据
    for (Note note : notes) {
      InsertSingleNote(note);
    }
  }
}
